<template>
  <el-popover
    placement="right"
    popper-class="node-tooltip-popover"
    :virtual-ref="triggerRef"
    virtual-triggering
    :visible="visible"
    :width="220"
  >
    <div class="node-tooltip-content">
      <div v-if="nodeData" class="tooltip-header">
        <div class="node-image">
          <img v-if="nodeData.image" :alt="nodeData.name" :src="nodeData.image" @error="onImageError" />
          <div v-else class="no-image">
            <el-icon><picture /></el-icon>
          </div>
        </div>
        <div class="node-info">
          <div class="node-name">{{ nodeData.name }}</div>
          <div v-if="nodeData.category" class="node-category">{{ nodeData.category }}</div>
        </div>
      </div>
      <div v-if="nodeData?.description" class="tooltip-description">
        {{ nodeData.description }}
      </div>
      <div v-if="!nodeData" class="no-data">正在加载节点信息...</div>
    </div>
  </el-popover>
</template>

<script setup lang="ts">
import axios from 'axios'
import { computed, onMounted, ref, watch } from 'vue'
import { getAntvNode } from '/@/api/antvx6'

// 定义 Props 接口
interface Props {
  visible: boolean
  triggerRef?: HTMLElement
  nodeId?: string
  nodeType?: string
}

// 定义 props
const props = withDefaults(defineProps<Props>(), {
  visible: false,
  triggerRef: undefined,
  nodeId: '',
  nodeType: '',
})

// 调试功能
const debug = (message: string, data?: any) => {
  // console.log(`[NodeTooltip] ${message}`, data)
}

// 节点数据状态
const nodePropertiesData = ref<any>(null)
const loading = ref(true)

// 计算节点数据
const nodeData = computed(() => {
  if (!nodePropertiesData.value || !props.nodeType) {
    return null
  }

  const nodeRegistration = nodePropertiesData.value.nodeRegistrations?.find((reg: any) => reg.nodeType === props.nodeType)

  if (!nodeRegistration) {
    debug('Node registration not found for:', props.nodeType)
    return null
  }

  // 获取图像路径
  let imagePath = ''
  if (nodeRegistration.stencilConfig?.[0]?.attrs?.image?.['xlink:href']) {
    imagePath = nodeRegistration.stencilConfig[0].attrs.image['xlink:href']
  } else if (nodeRegistration.shape?.attrs?.image?.['xlink:href']) {
    imagePath = nodeRegistration.shape.attrs.image['xlink:href']
  }

  return {
    name: nodeRegistration.name || props.nodeType,
    category: nodeRegistration.category || '',
    description: nodeRegistration.description || '',
    image: imagePath,
  }
})

// 加载节点属性数据
const loadNodeProperties = async () => {
  try {
    loading.value = true

    //   // 尝试从 fetch 加载
    //   const response = await fetch('/src/views/index/mockData/nodeProperties.json')
    //   if (response.ok) {
    //     nodePropertiesData.value = await response.json()
    //     debug('Properties loaded from fetch')
    //   } else {
    //     throw new Error('Fetch failed')
    //   }
    // } catch {
    //   try {
    //     // 备用方案：动态导入
    //     const module = await import('../mockData/nodeProperties.json')
    //     nodePropertiesData.value = module.default
    //     debug('Properties loaded from import')
    //   } catch (importError) {
    //     console.error('Failed to load node properties:', importError)
    //   }

    // 使用axios从接口加载
    const response = await getAntvNode()
    nodePropertiesData.value = response
  } catch (error) {
    console.error('Failed to load node properties:', error)
  } finally {
    loading.value = false
  }
}


// 图片加载错误处理
const onImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  console.warn('Failed to load image:', img.src)
}

// 监听属性变化
watch(
  () => props.visible,
  (newVal) => {
    debug('Visibility changed:', newVal)
  }
)

watch(
  () => props.nodeType,
  (newVal) => {
    debug('Node type changed:', newVal)
  }
)

// 组件挂载
onMounted(() => {
  loadNodeProperties()
})

// 暴露组件名称用于调试
defineOptions({
  name: 'NodeTooltip',
})
</script>

<script lang="ts">
// 添加默认导出以支持默认导入
export default {
  name: 'NodeTooltip',
}
</script>

<style scoped>
.node-tooltip-content {
  padding: 12px;
}

.tooltip-header {
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.node-image {
  display: flex;
  flex-shrink: 0;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  background-color: #f5f5f5;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
}

.node-image img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.no-image {
  font-size: 20px;
  color: #999;
}

.node-info {
  flex: 1;
  min-width: 0;
}

.node-name {
  margin-bottom: 4px;
  font-size: 14px;
  font-weight: 600;
  color: #333;
  overflow-wrap: break-word;
}

.node-category {
  display: inline-block;
  padding: 2px 6px;
  font-size: 12px;
  color: #666;
  background-color: #f0f2f5;
  border-radius: 3px;
}

.tooltip-description {
  margin-top: 8px;
  font-size: 12px;
  line-height: 1.4;
  color: #666;
  overflow-wrap: break-word;
}

.no-data {
  padding: 8px;
  font-size: 12px;
  color: #999;
  text-align: center;
}
</style>

<style>
.node-tooltip-popover {
  max-width: 280px !important;
}

.node-tooltip-popover .el-popover__content {
  padding: 0 !important;
}
</style>
